package com.ossjk.api.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.ossjk.oa.system.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.ossjk.core.base.controller.BaseController;
import com.ossjk.core.util.CommonMethod;
import com.ossjk.core.util.CommonUtil;
import com.ossjk.core.util.Constant;
import com.ossjk.core.util.CryptoUtils;
import com.ossjk.oa.accounting.service.ICwCapitalsService;
import com.ossjk.oa.accounting.service.ICwCpttypesService;
import com.ossjk.oa.accounting.vo.StatisticsVo;
import com.ossjk.oa.attendance.entity.Attendance;
import com.ossjk.oa.attendance.service.IAttendanceService;
import com.ossjk.oa.finance.entity.Reimburse;
import com.ossjk.oa.finance.service.IReimburseService;
import com.ossjk.oa.finance.service.ISubreimburseService;
import com.ossjk.oa.finance.vo.ReimVo;
import com.ossjk.oa.system.service.IAttachmentService;
import com.ossjk.oa.system.service.IDepartmentService;
import com.ossjk.oa.system.service.IEmployeePostService;
import com.ossjk.oa.system.service.IEmployeeService;
import com.ossjk.oa.system.service.IPostService;
import com.ossjk.oa.system.service.ITokenService;
import com.ossjk.oa.system.vo.EmpVo;


//RESTful 规范1234567890-98765432134567uiop90876543
///12345678798o8i7y5t34253657890998oi7654343
//撒大范甘迪活佛济公开好了看、看美女吧
@RestController
//@Controller
//@ResponseBody //放到类型上整个 ApiController都是返回json数据
@RequestMapping("/api")
public class ApiController extends BaseController {

	@Autowired
	private ICwCapitalsService iCwCapitalsService;
	@Autowired
	private IEmployeeService iEmployeeService;
	@Autowired
	private IPostService iPostService;
	@Autowired
	private IEmployeePostService iEmployeePostService;
	@Autowired
	private IDepartmentService iDepartmentService;
	@Autowired
	private ITokenService iTokenService;
	@Autowired
	private IReimburseService iReimburseService;
	@Autowired
	private ISubreimburseService iSubreimburseService;
	@Autowired
	private IAttachmentService iAttachmentService;
	@Autowired
	private IAttendanceService iAttendanceService;

	@Autowired
	private ICwCpttypesService  iCwCpttypesService;

	@GetMapping("/cptInuse")
	public Object findCwCpttypesInuse( ) {
		return responseSuccess(iCwCpttypesService.selectCwCpttypesInuse());
	}

////	@RequestMapping(value = "lgn",method = RequestMethod.POST) //http请求就可以接收，能不能指定只接收某个请求
//	@PostMapping("/lgn")    //只接收post请求
//	public Object login(String nm, String pwd) {
////		responseSuccess()//成功
////		responseFail()//失败
////		responseException()//异常
//		return responseSuccess(Constant.RESPONSE_MSG_SUCCESS, tokenStr);
//	}


	@PostMapping("/lgn")
	public Object login(String nm, String pwd) {

		// 分配token
		Wrapper wrapper = Condition.create().eq("name", nm);
		Employee employee = iEmployeeService.selectOne(wrapper);
		if (!CommonUtil.isBlank(employee)
				&& CommonUtil.isEquals(employee.getPwd(), CryptoUtils.encodeMD5(new String(pwd)))) {





			Token token = new Token();
			token.setUid(employee.getId());
			String tokenStr = jwtTokenUtil.generalToken(employee.getId(), employee.getName());
			token.setDuration(jwtTokenUtil.getTokenTimeOut(tokenStr));
			token.setToken(tokenStr);

			Map expression = new HashMap();
			// 岗位id
			Wrapper wrapper2 = Condition.create().eq("eid", employee.getId());
			EmployeePost employeePost = iEmployeePostService.selectOne(wrapper2);
			expression.put(Constant.REQUEST_PID_KEY, employeePost.getPid());
			// 部门id
			Post post = iPostService.selectById(employeePost.getPid());
			expression.put(Constant.REQUEST_DID_KEY, post.getDid());
			Wrapper wrapper3 = Condition.create();
			List<Department> departments = iDepartmentService.selectList(wrapper3);
			// List dsub = new ArrayList();
			// dsub.add(post.getDid());
			List dsub = iDepartmentService.selectSubIdByPid(post.getDid());
			dsub.add(post.getDid());
			expression.put(Constant.REQUEST_DSUB_KEY, dsub);
			Wrapper wrapper4 = Condition.create();
			List<Post> posts = iPostService.selectList(wrapper4);
			// List psub = new ArrayList();
			// psub.add(employeePost.getPid());
			List psub = iPostService.selectSubIdByPid(post.getId());
			psub.add(post.getId());
			expression.put(Constant.REQUEST_PSUB_KEY, psub);
			token.setExpression(JSON.toJSONString(expression));


			iTokenService.insertNewToken(token);

			return responseSuccess(Constant.RESPONSE_MSG_SUCCESS, tokenStr);
		} else {
			return responseFail("登录失败");
		}
	}


	@GetMapping("/getMe")
	public Object getUser() {
		// 查询用户信息
		String eid = getCurrnetUserId();
		Employee employee = iEmployeeService.selectById(eid);
		Map me = new HashMap();
		me.put("nm", employee.getRname());
		me.put("id", employee.getId());

		Post post = iPostService.findPostByEid(employee.getId());
		me.put("pnm", post.getName());
		me.put("lv", post.getLevel());

		if (post.getLevel().intValue() == 3) { // 只记录二级以上部门ID
			Department dpt = iDepartmentService.selectById(post.getPid());
			me.put("dnm", dpt.getName());
			me.put("did", dpt.getId());
		} else {
			me.put("dnm", post.getRemarks());
			me.put("did", post.getId());
		}

		return responseSuccess(me);
	}

	@PostMapping("/addReim")
	public Object insert(Reimburse reimburse, String[] sname, String[] samount, String[] sisreceipt,
						 String[] sremarks) {

		String eid = getCurrnetUserId();

		reimburse.setRwst(new BigDecimal(1));
		if (iReimburseService.insert(reimburse, sname, samount, sisreceipt, sremarks)) {
			return responseSuccess(reimburse.getId());
		} else {
			return responseFail();
		}
	}

	/**
	 *  //取得报销导航
	 * @param mth
	 * @return
	 */
	@GetMapping("/rmNavi")    //取得报销导航
	public Object listRMByMth(String mth ) {
		if (mth == null) {
			Calendar now = Calendar.getInstance();
			if (now.get(Calendar.DAY_OF_MONTH) > 20) {
				mth = CommonMethod.calMth(0, now.getTime()); // 默认本月
			} else {
				mth = CommonMethod.calMth(-1, now.getTime()); // 默认上月
			}
		}
		return responseSuccess(iReimburseService.selectPreNext(mth));
	}

	@GetMapping("/lsRm")
	public Object listRMByMth(String mth, Integer rwst) {
		// 查询用户信息
		String eid = getCurrnetUserId();
		EmpVo curEmp = iEmployeeService.selectOneEmpVoByID(eid);

		// 列表内容
		Wrapper wrapper = Condition.create().isWhere(true).orderBy("edtm", true).eq("left(edtm,7)", mth);
		Wrapper wrapper2 = null;

		// wrapper.getSqlSegment()
		if (curEmp.getPname().indexOf("总") >= 0) { // 总经理、总监、总顾问
			if (rwst == 1) {
				wrapper.eq("did", curEmp.getDid()); //
			}else {
				if (curEmp.getPname().indexOf("总监") >= 0) {
					wrapper.eq("did", curEmp.getDid());
				}
			}
		} else {
			wrapper.eq("eid", eid);
		}

		// wrapper.eq("rwst", rwst);
		List<ReimVo> datas = null;

		if (rwst == 1) {
			wrapper.eq("rwst", "1");
			datas = iReimburseService.selectVo(1, wrapper);
			// 补齐自己没通过的
			wrapper2 = Condition.create().isWhere(true).orderBy("edtm", true).eq("left(edtm,7)", mth);
			wrapper2.eq("eid", curEmp.getId()).eq("rwst", "3");
			datas.addAll( iReimburseService.selectVo(2, wrapper2));

			wrapper2 = Condition.create().isWhere(true).orderBy("edtm", true).eq("left(edtm,7)", mth);
			wrapper2.eq("eid", curEmp.getId()).eq("rwst", "6");
			datas.addAll(iReimburseService.selectVo(5, wrapper2));
			// 补齐自己没通过的 end

			//总经理补齐 所有人部门审批通过的
			if (curEmp.getPname().indexOf("总经") !=-1 ) { // 总经理
				wrapper2 = Condition.create().isWhere(true).orderBy("edtm", true).eq("left(edtm,7)", mth).eq("rwst", "2");
				datas.addAll(iReimburseService.selectVo(2, wrapper2));
			}

		} else if (rwst == 2) {

			wrapper.eq("rwst", "2");
			datas = iReimburseService.selectVo(2, wrapper);

			wrapper2 = Condition.create().isWhere(true).orderBy("edtm", true).eq("left(edtm,7)", mth);
			wrapper2.in("rwst", "5,7");
			if (curEmp.getPname().indexOf("总监") >=0 ){  //总监
				wrapper2.eq("did", curEmp.getDid()); // 自己部门 1：新增
			}else 	if (curEmp.getPname().indexOf("总经") >=0 ){// 总经理
				//全部
			}else {
				wrapper2.eq("eid", eid);
			}
			datas.addAll( iReimburseService.selectVo(5, wrapper2));
		}

		List rtnDatas = new ArrayList();
		Map rtnOne = null;
		if(datas!=null)
			for (ReimVo reimVo : datas) {
				rtnOne = new HashMap();
				rtnOne.put("rm", reimVo);
				rtnOne.put("sub", iSubreimburseService.selectByRid(reimVo.getId()));
				rtnDatas.add(rtnOne);
			}
		return responseSuccess(rtnDatas);
	}

	// 只上传附件
	// @PostMapping("/addReimAtta")
	@RequestMapping(value = "/addReimAtta", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Object 添加报销附件(String rid, MultipartFile mfile) {

		Reimburse reimburse = iReimburseService.selectById(rid);
		Attachment att = new Attachment();
		Employee user = iEmployeeService.selectById(this.getCurrnetUserId());

		att.setFile(user.getName() + "_" + reimburse.getName().trim() + "reim"
				+ CommonMethod.iso0Format.format(reimburse.getSttm()) + CommonUtil.random.nextInt(9999) + ".jpg");
		att.setEid(user.getId());

		att = iAttachmentService.uploadOneAttachment(att, mfile);

		if (att != null) {
			if (reimburse.getAttacid1() == null) {
				reimburse.setAttacid1(att.getId());
			} else {
				reimburse.setAttacid2(att.getId());
			}
			return responseSuccess(iReimburseService.updateById(reimburse));
		} else {
			return responseFail();
		}
	}

	// 删除报销
	@GetMapping("/delRm/{id}")
	public Object delete(@PathVariable("id") String id) {
		System.out.println(id);
		if (iReimburseService.deleteById(id)) {
			return responseSuccess();
		} else {
			return responseFail();
		}
	}

	@GetMapping("/spRm")
	public Object spRiem(String id, BigDecimal rwst, String rwrs) {

		String eid = getCurrnetUserId();
		Post post = iPostService.findPostByEid(eid);
		Reimburse reim = iReimburseService.selectById(id);
		if (post.getLevel().intValue() == 2) { // 部门总监以上级别才可以审批
			reim.setRwid(eid);
			reim.setRwrs(rwrs);
			reim.setRwtm(new Date());
			reim.setRwst(rwst);

		} else if (post.getLevel().intValue() == 1) {
			reim.setRwid2(eid);
			reim.setRwrs2(rwrs);
			reim.setRwtm2(new Date());
			reim.setRwst(rwst.add(BigDecimal.valueOf(3)));
		}

		return responseSuccess(iReimburseService.updateById(reim));
	}

	@GetMapping("/shCntRm")    //rwst可选，传递就是5不传就是7
	public Object countRiem( Integer rwst,String mth) {

		EmpVo curEmp = iEmployeeService.selectOneEmpVoByID(this.getCurrnetUserId());

		Wrapper wrapper = Condition.create().isWhere(false).eq("left(a.edtm,7)", mth).orderBy("d.did,a.crer", false).groupBy("a.crer,d.rname");

		if (curEmp.getPname().equals("市场总监")  || curEmp.getPname().indexOf("总经") >=0){  //总监
			if(rwst == null) {
				wrapper.eq("a.rwst", 7);
			}else {
				wrapper.eq("a.rwst", 5);
			}
		}else {
			wrapper.eq("a.rwst", 7);
			if (  curEmp.getPname().indexOf("总监") >=0){//其他总监
				wrapper.eq("d.did", curEmp.getDid());
			}else {//员工
				wrapper.eq("d.id", curEmp.getId());
			}
		}

		return responseSuccess( iReimburseService.selectMthVoCount( wrapper ) );
	}

	@PostMapping("/payRms")
	public Object payReims(  String eids[],   String mth,String  cptype ) {

		EmpVo curEmp = iEmployeeService.selectOneEmpVoByID(this.getCurrnetUserId());
		if (curEmp.getPname().equals("市场总监")   ){  //总监
			return iReimburseService.pays(eids,  mth,  cptype)?responseSuccess("支付成功"): responseFail("支付失败");
		}else {
			return responseFail("没有权限");
		}
	}

	@PostMapping("/payRm")
	public Object payReim(  String eid, int cnt ,String mth,String  cptype ) {
		// System.out.println("mth="+mth);
		EmpVo curEmp = iEmployeeService.selectOneEmpVoByID(this.getCurrnetUserId());
		if (curEmp.getPname().equals("市场总监")   ){  //总监
			return iReimburseService.pay(iEmployeeService.selectById(eid), cnt, mth, "手机单条录入", cptype)?responseSuccess("支付成功"): responseFail("支付失败");
		}else {
			return responseFail("没有权限");
		}
	}

	// 资金流水账统计
	@GetMapping("/tj")
	public Object list(Integer tp, String m1, String m2) {

		List<StatisticsVo> datas = null;
		if (tp == 1) {
			datas = iCwCapitalsService.statistics(tp, m1, m2);
		} else if (tp == 2) {
			datas = iCwCapitalsService.statistics(tp, m1, null);
		} else {
			datas = iCwCapitalsService.statistics(tp, m1, null);
		}
		return responseSuccess(datas);

	}

	///////////////// 考勤///////

	// 列出个人考勤
	@GetMapping("/lskq")
	public Object listKq(String eid, String mth) {

		Wrapper wrapper = Condition.create().isWhere(true).eq("ad.isdelete", "1").orderBy("date", false);

		if (!CommonUtil.isBlank(eid)) {
			wrapper.eq("ad.eid", eid);
		} else {
			// 默认查询自己
			wrapper.eq("ad.eid", getCurrnetUserId());
		}

		if (mth == null) {
			Calendar now = Calendar.getInstance();
			if (now.get(Calendar.DAY_OF_MONTH) > 15) {
				mth = CommonMethod.calMth(0, now.getTime()); // 默认本月
			} else {
				mth = CommonMethod.calMth(-1, now.getTime()); // 默认上月
			}
		}

		System.out.println("mth = " + mth);

		String yearMth[] = mth.split("-");
		wrapper.eq("ad.year", yearMth[0]).eq("ad.month", yearMth[1]);

		return responseSuccess(this.iAttendanceService.selectDetail(wrapper));

	}

	@GetMapping("/kqNavi")    //取得考勤报销导航
	public Object listKQByMth(String mth ) {
		if (mth == null) {
			Calendar now = Calendar.getInstance();
			if (now.get(Calendar.DAY_OF_MONTH) > 20) {
				mth = CommonMethod.calMth(0, now.getTime()); // 默认本月
			} else {
				mth = CommonMethod.calMth(-1, now.getTime()); // 默认上月
			}
		}
		return responseSuccess(iAttendanceService.selectPreNext(mth));
	}

	// 新增考勤
	@GetMapping("/addkq")
	public Object insertAttendance(Attendance attendance) {
		attendance.setEid(getCurrnetUserId());
		// 判断是否已有考勤记录
		// 格式化Date 如: yyyyMMdd
		String dateStr = CommonUtil.date0(attendance.getDate());
		// 年
		attendance.setYear(new BigDecimal(dateStr.substring(0, 4)));
		// 月
		attendance.setMonth(new BigDecimal(dateStr.substring(4, 6)));
		// 日
		attendance.setDay(new BigDecimal(dateStr.substring(6, 8)));
		Wrapper wrapper = Condition.create().eq("eid", attendance.getEid()).eq("year", attendance.getYear())
				.eq("month", attendance.getMonth()).eq("day", attendance.getDay());
		if (!CommonUtil.isBlank(iAttendanceService.selectOne(wrapper))) {
			return responseFail("已存在考勤记录");
		}
		// 查询该员工的部门
		Department department = iDepartmentService.selectByEid(attendance.getEid());
		// 设置部门id
		attendance.setDid(department.getId());
		// 异常
		attendance.setStat(new BigDecimal(2));
		// 待审核
		attendance.setRwst(new BigDecimal(1));
		if (iAttendanceService.insert(attendance)) {
			return responseSuccess();
		} else {
			return responseFail();
		}
	}

	// 操作考勤
	@GetMapping("/optkq")
	public Object updateAttendance(String id, String remarks, Integer rwst, String rwrs) {

		Attendance attendance = iAttendanceService.selectById(id);

		if (remarks != null) {
			attendance.setRemarks(remarks);
			attendance.setRwst(new BigDecimal(1)); // 待审核
		} else {
			attendance.setRwst(new BigDecimal(rwst));
			attendance.setStat(rwst==2?new BigDecimal(1):new BigDecimal(2));
			attendance.setRwtm(new Date()); // 审核人
			attendance.setRwid(getCurrnetUserId());
			attendance.setRwrs(rwrs); // 待审核
		}

		if (iAttendanceService.updateById(attendance)) {
			return responseSuccess();
		} else {
			return responseFail();
		}
	}

	// 列出部门
	@GetMapping("/lsdpt")
	public Object listDepartment() {
		return responseSuccess(iDepartmentService.selectVo());
	}

	// 列出部门员工
	@GetMapping("/lsemps")
	public Object listEmployeeVos(String did) {
		return responseSuccess(iEmployeeService.selectEmpVosByDid(did));

	}

}
